package com.fancy.learncenter.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.OnlyInfoBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.RSA;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class ForgetPSWActivity extends BaseActivity {


    @Bind(R.id.tel_edit)
    EditText telEdit;
    @Bind(R.id.account_delete)
    ImageView accountDelete;
    @Bind(R.id.code_edit)
    EditText codeEdit;
    @Bind(R.id.code_bt)
    Button codeBt;
    @Bind(R.id.password_edit)
    EditText passwordEdit;
    @Bind(R.id.password_again_edit)
    EditText passwordAgainEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_psw, Status.STATUS);
        ButterKnife.bind(this);
    }

    private void getCode() {

        HttpMehtod.getInstance().getPWDCode(telEdit.getText().toString(), new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<OnlyInfoBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), OnlyInfoBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack() {

                    @Override
                    public void success(Object dataBean) {

                    }

                    @Override
                    public void fail(String errorCode) {

                    }

                }).dealData();
            }
        });
    }

    private void find() {

        if (!Utils.isMobileNO(telEdit.getText().toString())) {
            ToastUtil.show("请输入正确的手机号码");
            return;
        }

        if (TextUtils.isEmpty(codeEdit.getText().toString())) {
            ToastUtil.show("验证码不能为空");
            return;
        }

        if (TextUtils.isEmpty(passwordEdit.getText().toString())) {
            ToastUtil.show("密码不能为空");
            return;
        }
        if (!passwordEdit.getText().toString().equals(passwordAgainEdit.getText().toString())) {
            ToastUtil.show("两次密码不一致");
            return;
        }

        String rsaStr = "";
        try {
            rsaStr = RSA.ecrypt(Constant.loginToken + passwordAgainEdit.getText().toString(), Constant.RSA_PUBLIC_KEY, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map map = new HashMap();
        map.put("vCode", codeEdit.getText().toString());

        map.put("newPassword", rsaStr);

        map.put("mobile", telEdit.getText().toString());

        HttpMehtod.getInstance().findPWD(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                //解析数据
                BaseBean<OnlyInfoBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), OnlyInfoBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<OnlyInfoBean>() {
                    @Override
                    public void success(OnlyInfoBean dataBean) {

                        ToastUtil.show("密码修改成功");
                        Intent intent = new Intent(ForgetPSWActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void fail(String errorCode) {

                        ToastUtil.show("密码修改失败，请稍后再试");
                    }
                }).dealData();


            }
        });
    }


    private Subscription subscribe_auto;

    int currentTime = 60;

    private void autoLoop() {
        if (!Utils.isMobileNO(telEdit.getText().toString())) {
            ToastUtil.show("请输入正确的手机号");
        }

        getCode();
        codeBt.setEnabled(false);
//        codeBt.setBackgroundColor(Color.parseColor("#8001D7A7"));
        currentTime = 60;
        codeBt.setText("" + currentTime);
        if (subscribe_auto == null || subscribe_auto.isUnsubscribed()) {
            subscribe_auto = Observable.interval(1, 1, TimeUnit.SECONDS)
                    //延时3000 ，每间隔3000，时间单位
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            currentTime--;
                            codeBt.setText(currentTime + "  S");
                            if (currentTime <= 0) {
                                stopLoop();
                            }
                        }
                    });
        }
    }

    private void stopLoop() {
        codeBt.setEnabled(true);
        codeBt.setText("获取验证码");
//        codeBt.setBackgroundColor(Color.parseColor("#01D7A7"));
        if (subscribe_auto != null && !subscribe_auto.isUnsubscribed()) {
            subscribe_auto.unsubscribe();
        }
    }



    @OnClick({R.id.account_delete, R.id.back_image, R.id.code_bt, R.id.password_delete, R.id.password_again_delete, R.id.regist_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_image:
                finish();
            case R.id.account_delete:
                telEdit.setText("");
                break;
            case R.id.code_bt:
                autoLoop();
                break;
            case R.id.password_delete:
                passwordEdit.setText("");
                break;
            case R.id.password_again_delete:
                passwordAgainEdit.setText("");
                break;
            case R.id.regist_bt:
                find();
                break;
        }
    }
}
